package com.doubao.device.config;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

/**
 * Device模块的RestTemplate配置类
 */
@Configuration(value = "deviceRestTemplateConfig")
public class RestTemplateConfig {

    /**
     * 创建RestTemplate Bean实例
     *
     * @return RestTemplate实例
     */
    @Bean(name = "deviceRestTemplate")
    public RestTemplate deviceRestTemplate(RestTemplateBuilder builder) {
        return builder
                .setConnectTimeout(Duration.ofSeconds(5))
                .setReadTimeout(Duration.ofSeconds(30))
                .requestFactory(this::simpleClientHttpRequestFactory)
                .build();
    }

    /**
     * 创建ClientHttpRequestFactory实例
     *
     * @return ClientHttpRequestFactory实例
     */
    private ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5000);  // 连接超时，单位毫秒
        factory.setReadTimeout(30000);    // 读取超时，单位毫秒
        // 移除已过时的方法
        // factory.setBufferRequestBody(false);  // 不缓存请求体
        return factory;
    }
}